package com.bianmaba;

/**
 * @program: hadoop-samples
 * @description:
 * @author: Chenjiabin
 * @create: 2019/7/11 15:09
 **/

import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.data.hadoop.hive.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;


//由于spring-data-hadoop版本太旧，已经停止更新，导致部份代码出现问题
//这里test1执行时会提示缺少HiveServerException,我们手动创建了一个org.apache.hadoop.hive.service.HiveServerException
public class Test01 {
    private ApplicationContext context = null;
    BasicDataSource bds;
    HiveTemplate hiveTemplate = null;

    @Before
    public void before() throws Exception {
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName("org.apache.hive.jdbc.HiveDriver");
        bds.setUrl("jdbc:hive2://192.168.1.10:10000/default");
        bds.setMaxTotal(10);
        bds.setMaxIdle(1);
        bds.setMinIdle(1);
        HiveClientFactoryBean hiveClientFactoryBean = new HiveClientFactoryBean();
        hiveClientFactoryBean.setHiveDataSource(bds);
        hiveClientFactoryBean.afterPropertiesSet();
        HiveClientFactory factory = hiveClientFactoryBean.getObject();

        hiveTemplate = new HiveTemplate(factory);
    }

    @Test
    public void test02() {
        //2.利用hiveTemplate查询hive
        List<Info> list = hiveTemplate.execute(new HiveClientCallback<List<Info>>() {
            public List<Info> doInHive(HiveClient hiveClient) throws Exception {
                List<Info> list = new ArrayList<Info>();
                Connection conn = hiveClient.getConnection();
                PreparedStatement ps = conn.prepareStatement("select * from info");
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    Info stu = new Info();
                    stu.setId(rs.getString("id"));
                    stu.setName(rs.getString("name"));
                    list.add(stu);
                }
                return list;
            }
        });
        //3.打印结果
        System.out.println(list);
    }


    @Test
    public void test01() {
        //2.利用hiveTemplate查询hive
        List<String> list = hiveTemplate.query("select * from info");
        System.out.println(list);
    }
}